//
//  XSImageEditViewController.m
//  AudioVideo
//
//  Created by xueshan1 on 2019/9/19.
//  Copyright © 2019 xueshan1. All rights reserved.
//

#import "XSImageEditViewController.h"
#import "XSImageClipView.h"
#import "XSImageGridView.h"
#import "XSImageFilterView.h"
#import "XSImageEditViewController+clip.h"
#import "XSVideoWaterPrintEditeView.h"
#import "XSVideoWaterPrintView.h"

@interface XSImageEditViewController ()

@property (weak, nonatomic) IBOutlet UIView *navBarView;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
@property (weak, nonatomic) IBOutlet UIButton *doneBtn;
@property (weak, nonatomic) IBOutlet UIButton *clipBtn;
//@property (weak, nonatomic) IBOutlet UIButton *ratioBtn;
@property (weak, nonatomic) IBOutlet UIButton *filterBtn;
@property (weak, nonatomic) IBOutlet UIButton *rotateBtn;
@property(nonatomic,strong)UIPanGestureRecognizer *panImageViewGesture;

@property(nonatomic,strong)XSImageGridView *gridView;
@property(nonatomic,strong)UIView *topLeftView;
@property(nonatomic,strong)UIView *topRightView;
@property(nonatomic,strong)UIView *botLeftView;
@property(nonatomic,strong)UIView *botRightView;

@property (weak, nonatomic) IBOutlet UIView *barBgView;

@property(nonatomic,strong)XSImageRatioToolBarView* ratioBarView;
@property(nonatomic,strong)XSImageFilterView *fileterBarView;
@property(nonatomic,strong)XSVideoWaterPrintEditeView *waterEditView;


@end

@implementation XSImageEditViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
}
- (void)isIphoneX{
    self.navBarView.height = 83;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor blackColor];
    
 

}

- (void)setupUI{
    if (self.photoModel) {
        [XSPhotosManager requestImageWithModel:self.photoModel completion:^(UIImage *image, NSDictionary *info) {
            self.originImage = image;
        }];
    }else if(self.photo){
        self.originImage = self.photo;
    }
  
    
}

#pragma mark - action
- (IBAction)cancelBtnClicked:(id)sender {
    [self.navigationController popViewControllerAnimated:NO];
    
}
//
- (IBAction)doneBtnClicked:(id)sender {
    //裁剪
    UIImage *newImage = [self clipImage];
    CGFloat zoomScale = self.imageView.bounds.size.width / self.imageView.image.size.width;
    CGRect rct = CGRectEqualToRect(self.clippingRect, CGRectZero) ? self.imageView.bounds : self.clippingRect;
    rct.size.width  /= zoomScale;
    rct.size.height /= zoomScale;
    rct.origin.x    /= zoomScale;
    rct.origin.y    /= zoomScale;
    
    CGPoint origin = CGPointMake(-rct.origin.x, -rct.origin.y);
    UIImage *img = nil;
    
    UIGraphicsBeginImageContextWithOptions(rct.size, NO, self.imageView.image.scale);
    [self.imageView.image drawAtPoint:origin];

     //水印
    XSVideoWaterPrintView * waterPrint = (XSVideoWaterPrintView *)[self.imageView subViewOfClassName:@"XSVideoWaterPrintView"];
    if (waterPrint) {
        waterPrint.hightlight = NO;
        CGRect wRect = waterPrint.frame;
        wRect.size.width  /= zoomScale;
        wRect.size.height /= zoomScale;
        wRect.origin.x    /= zoomScale;
        wRect.origin.y  = wRect.origin.y / zoomScale - 10;
        [waterPrint drawViewHierarchyInRect:wRect afterScreenUpdates:YES];
    }
  
    img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [XSPhotosManager saveImageToAblum:img completion:^(BOOL success, PHAsset *asset) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (success) {
                [self.navigationController popViewControllerAnimated:NO];
            }
        });
       
    }];
  
}


- (IBAction)clipBtnClicked:(id)sender {
    [self hideOtherView];
    self.gridView.hidden = NO;
    self.topLeftView.hidden = NO;
    self.topRightView.hidden = NO;
    self.botLeftView.hidden = NO;
    self.botRightView.hidden = NO;
    self.panImageViewGesture.enabled = YES;

    [UIView animateWithDuration:0.5 animations:^{
        self.ratioBarView.hidden = NO;
    }];
}

- (IBAction)ratioBtnClicked:(id)sender {
    [self hideOtherView];
 
    
}

- (IBAction)filterAction:(id)sender {
    [self hideOtherView];
    [self.fileterBarView showFilterView];
 
}

- (IBAction)roateBtnClicked:(id)sender {
    [self hideOtherView];

}

- (void)hideOtherView{
    _gridView.hidden = YES;
    _topLeftView.hidden = YES;
    _topRightView.hidden = YES;
    _botLeftView.hidden = YES;
    _botRightView.hidden = YES;
    self.panImageViewGesture.enabled = NO;
    
    _fileterBarView.hidden = YES;
    _ratioBarView.hidden = YES;
    
}

- (IBAction)resetAction:(id)sender {
    if (!self.fileterBarView.isHidden) {
        [self.fileterBarView resetFilter];
    }
    self.imageView.image = self.originImage;
    
    for (UIView *subV in self.imageView.subviews) {
        if ([subV isKindOfClass:[XSVideoWaterPrintView class]]) {
            [subV removeFromSuperview];
        }
    }
}

- (IBAction)watermarkAction:(id)sender {
    [self hideOtherView];
    [self.view addSubview:self.waterEditView];
    [self.waterEditView appear];
    
}

#pragma mark - getter

- (XSImageFilterView *)fileterBarView{
    if (!_fileterBarView) {
        _fileterBarView = [[XSImageFilterView alloc]initWithFrame:CGRectMake(0, kHeight, kWidth, 120) editedImage:self.originImage editedView:self.imageView];
        [self.view addSubview:_fileterBarView];
        _fileterBarView.hidden = YES;
        WeakSelf
        _fileterBarView.finishFilterCallBack = ^(UIImage * _Nonnull filterImage) {
            weakSelf.imageView.image = filterImage;
        };
    }
    return _fileterBarView;
}

- (UIView *)ratioBarView{
    if (!_ratioBarView) {
        CGFloat W = 70;
        //压缩
        CGSize  imgSize = self.originImage.size;
        CGFloat maxW = MIN(imgSize.width, imgSize.height);
        UIImage *iconImage = [self scaleImage:self.originImage toSize:CGSizeMake(W * imgSize.width/maxW, W * imgSize.height/maxW)];
        
        _ratioBarView = [[XSImageRatioToolBarView alloc]initWithFrame:self.barBgView.bounds iconImage:iconImage];
        [self.barBgView addSubview:_ratioBarView];
        _ratioBarView.hidden = YES;
        WeakSelf
        _ratioBarView.currentSelectRatioBlock = ^(XSImageRatio *ratio) {
            weakSelf.selectedRatio = ratio;
        };
         
    }
    return _ratioBarView;
}

- (UIImageView *)imageView{
    if (!_imageView) {
        _imageView = [[UIImageView alloc]initWithFrame:CGRectZero];
        _imageView.contentMode = UIViewContentModeScaleAspectFit;
        _imageView.userInteractionEnabled = YES;
        [self.view addSubview:_imageView];
        
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGridView:)];
        [_imageView addGestureRecognizer:panGesture];
        panGesture.enabled = NO;
        self.panImageViewGesture = panGesture;
        
    }
    return _imageView;
}
- (XSImageGridView *)gridView{
    if (!_gridView) {
        _gridView = [[XSImageGridView alloc]initWithFrame:CGRectZero];
        _gridView.backgroundColor = [UIColor clearColor];
        [self.imageView addSubview:_gridView];
        _gridView.hidden = YES;
    }
    return _gridView;
}
- (UIView *)topLeftView{
    if (!_topLeftView) {
        _topLeftView = [self clippingCircleWithTag:0];
    }
    return _topLeftView;
}
- (UIView *)botLeftView{
    if (!_botLeftView) {
        _botLeftView = [self clippingCircleWithTag:1];
    }
    return _botLeftView;
}
- (UIView *)topRightView{
    if (!_topRightView) {
        _topRightView = [self clippingCircleWithTag:2];
    }
    return _topRightView;
}

- (UIView *)botRightView{
    if (!_botRightView) {
        _botRightView = [self clippingCircleWithTag:3];
    }
    return _botRightView;
}
- (UIView *)clippingCircleWithTag:(NSInteger)tag{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 22, 22)];
    view.layer.cornerRadius = view.width/2;
    view.layer.masksToBounds = YES;
    view.backgroundColor = [UIColor whiteColor];
    view.tag = tag;
    [self.view addSubview:view];
    view.hidden = YES;
    
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panCircleView:)];
    [view addGestureRecognizer:panGesture];
    return view;
}

- (XSVideoWaterPrintEditeView *)waterEditView{
    if (!_waterEditView) {
        _waterEditView = [[XSVideoWaterPrintEditeView alloc]initWithFrame:self.view.bounds];
        WeakSelf
        _waterEditView.confirmEditBlock = ^(NSString *str,UIColor *waterColor) {
            if (str.length) {
                //创建一个水印
                CGFloat hei = [str getSizeWithFontSize:WaterLabFont maxWidth:200].height;
                XSVideoWaterPrintView *waterPrint = [[XSVideoWaterPrintView alloc]initWithFrame:CGRectMake(0, 0, weakSelf.imageView.width - 20 , hei + 10)];
                waterPrint.y = (weakSelf.imageView.height - waterPrint.height)/2;
                waterPrint.textColor = waterColor;
                waterPrint.text = str;
                [weakSelf.imageView  addSubview:waterPrint];
                
            }
            
        };
        _waterEditView.cancelEditBlock = ^{
            
        };
        _waterEditView.selectImageFinishBlock = ^(UIImage *waterImage) {
            if (waterImage) {
                //创建一个水印
                XSVideoWaterPrintView *waterPrint = [[XSVideoWaterPrintView alloc]initWithFrame:CGRectMake(0, 0, waterImage.size.width + 20, waterImage.size.height + 20) waterType:VideoWaterPrintType_Image];
                waterPrint.y = (weakSelf.imageView.height - waterPrint.height)/2;
                //waterPrint.textColor = [UIColor lightGrayColor];
                waterPrint.waterImage = waterImage;
                [weakSelf.imageView  addSubview:waterPrint];

            }
        };
    }
    return _waterEditView;
}

#pragma mark - setter
- (void)setOriginImage:(UIImage *)originImage{
    _originImage = originImage;
    self.imageView.image = originImage;
    [self resetImageViewFrameWithImage:originImage];
}
- (void)resetImageViewFrameWithImage:(UIImage *)image{
    if (!image) return;
    CGFloat wid = kWidth - 40;
    CGFloat maxHei = kHeight - self.navBarView.height - 180;
    
    CGFloat hei = wid * image.size.height/image.size.width;
    if (hei > maxHei) {
        hei = maxHei;
        wid = hei * image.size.width/image.size.height;
    }
    //init
    self.imageView.frame = CGRectMake((kWidth - wid)/2, self.navBarView.bottom + 20, wid, hei);
    self.gridView.frame = self.imageView.bounds;
    self.gridView.clipRect = self.gridView.bounds;
    
    CGRect clipRect = self.imageView.frame;
    CGFloat x =  clipRect.origin.x;
    CGFloat y =  clipRect.origin.y;
    CGFloat wid_img = clipRect.size.width;
    CGFloat hei_img = clipRect.size.height;
    self.topLeftView.center = CGPointMake(x , y);
    self.topRightView.center = CGPointMake(x + wid_img, y);
    self.botLeftView.center = CGPointMake(x , y + hei_img);
    self.botRightView.center = CGPointMake(x + wid_img, y + hei_img);
    
    //default 相对imageView的
    _clippingRect = self.imageView.bounds;
    
}

- (void)setClippingRect:(CGRect)clippingRect{
    _clippingRect = clippingRect;
    
    [self resetCornerViewFrame:clippingRect];
    self.gridView.clipRect = clippingRect; //相对imageView的
}

- (void)resetCornerViewFrame:(CGRect)clipRect{
    CGFloat x =  clipRect.origin.x;
    CGFloat y =  clipRect.origin.y;
    CGFloat wid = clipRect.size.width;
    CGFloat hei = clipRect.size.height;
    
    self.topLeftView.center = [self.view convertPoint:CGPointMake(x , y) fromView:_imageView];
    self.topRightView.center = [self.view convertPoint:CGPointMake(x + wid, y) fromView:_imageView];
    self.botLeftView.center = [self.view convertPoint:CGPointMake(x , y + hei) fromView:_imageView];
    self.botRightView.center = [self.view convertPoint: CGPointMake(x + wid, y + hei) fromView:_imageView];
    
}

- (void)setSelectedRatio:(XSImageRatio *)selectedRatio{
    _selectedRatio = selectedRatio;
    [self clipRatioChanged];
}

- (void)clipRatioChanged{
    CGRect rect = _imageView.bounds;
    if (self.selectedRatio) {
        CGFloat H = rect.size.width * self.selectedRatio.ratio;
        if (H <= rect.size.height) {
            rect.size.height = H;
        } else {
            rect.size.width *= rect.size.height / H;
        }
        
        rect.origin.x = (_imageView.bounds.size.width - rect.size.width) / 2;
        rect.origin.y = (_imageView.bounds.size.height - rect.size.height) / 2;
        
    }
    
    [self setClippingRect:rect];

}



 


@end
